import { type Context, type PluginData } from '@abmao/pkgs'

export default function createPackagesPlugin(): PluginData {
  return {
    id: 'packages',
    command: 'packages',
    description: 'get work packages',
    action: commandPackages,
  }
}
export async function parsecCommandPackages(context: Context): Promise<string[]> {
  // 获取工作区包目录路径，包括直接和间接依赖这些包的包
  const files = await context.fileStore.workDiffFile()
  // 通过扑排序返回直接和间接这些包的依赖包
  const packageDirList = context.contextAnalysisDiagram.getMyRelyDir(files)

  const packageNameList = packageDirList
    // 包目录映射到对应的图表，拿到包名
    .map(dir => context.contextAnalysisDiagram.dirToAnalysisBlock(dir)?.name)
    .filter(name => name) as string[]
  return packageNameList
}

export async function commandPackages(context: Context): Promise<string[]> {
  // 接收命令
  const packageNameList = await parsecCommandPackages(context)
  // 序列化成字符串
  const logStr = packageNameList.reduce((previousValue, currentValue) => {
    return `${previousValue}\n${currentValue}`
  }, '')
  // 打印命令
  console.log(logStr)
  return packageNameList
}
